//
//  RegistViewController.m
//  SportSocial
//
//  Created by yull on 14/11/27.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "RegistViewController.h"
#import "LoginTextField.h"
#import "UIColor+MethodExt.h"
#import "LoginRegistNet.h"
#import "RegistTwoViewController.h"

@interface RegistViewController () <UIActionSheetDelegate,UITextFieldDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) LoginTextField *accountTextField;

@property (nonatomic, strong) LoginTextField *mobileTextField;

@property (nonatomic, strong) LoginTextField *passwordTextField;

@property (nonatomic, strong) LoginTextField *verifyTextField;

@property (nonatomic, strong) UIButton *verifyButton;

@property (nonatomic, assign) NSInteger time;

@property (nonatomic, strong) NSTimer *timer;

@end

@implementation RegistViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationController.navigationBarHidden = YES;
    
    [self initSubViews];
    
    self.time = 60;
}

- (void)initSubViews
{
    UIImageView *backgroundImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    backgroundImageView.image = [UIImage imageNamed:@"left_bg"];
    [self.view addSubview:backgroundImageView];
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.scrollView = scrollView;
    [self.view addSubview:scrollView];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(5, Statebar_Height + 7, 40, 40);
    [backButton setImage:[UIImage imageNamed:@"btn_back_normal"] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:@"btn_back_pressed"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(onBackButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    
    if (!self.isFromForgotPW) {
        UIButton *forgotPWButton = [UIButton buttonWithType:UIButtonTypeCustom];
        forgotPWButton.frame = CGRectMake(self.view.width - 5 - 60, Statebar_Height + 7, 60, 40);
        forgotPWButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [forgotPWButton setTitle:@"忘记密码" forState:UIControlStateNormal];
        [forgotPWButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [forgotPWButton addTarget:self action:@selector(onForgotPWButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:forgotPWButton];
    }
    
    NSDictionary *dict = @{NSForegroundColorAttributeName:RGB(221.0f, 145.0f, 130.0f),
                           NSFontAttributeName:[UIFont boldSystemFontOfSize:18.0f]};
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(20, 100, self.view.width-40, 0.5)];
    lineView.backgroundColor = [UIColor whiteColor];
    
    if (!self.isFromForgotPW) {
        
        [scrollView addSubview:lineView];
        
        self.accountTextField = [[LoginTextField alloc] initWithFrame:CGRectMake(20, lineView.bottom, self.view.width - 40, 60)];
        self.accountTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入账号" attributes:dict];
        UIImageView *accountImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"leftbar_user"]];
        self.accountTextField.leftView = accountImageView;
        self.accountTextField.leftViewMode = UITextFieldViewModeAlways;
        self.accountTextField.delegate = self;
        [scrollView addSubview:self.accountTextField];
        
        lineView = [[UIView alloc] initWithFrame:CGRectMake(20, self.accountTextField.bottom, self.view.width-40, 0.5)];
        lineView.backgroundColor = [UIColor whiteColor];
    }
    
    [scrollView addSubview:lineView];
    
    self.mobileTextField = [[LoginTextField alloc] initWithFrame:CGRectMake(20, lineView.bottom, self.view.width - 40, 60)];
    self.mobileTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入手机号" attributes:dict];
    
    UIImageView *mobileImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"leftbar_user"]];
    self.mobileTextField.leftView = mobileImageView;
    self.mobileTextField.leftViewMode = UITextFieldViewModeAlways;
    self.mobileTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.mobileTextField.delegate = self;
    [scrollView addSubview:self.mobileTextField];
    
    lineView = [[UIView alloc] initWithFrame:CGRectMake(20, self.mobileTextField.bottom, self.view.width-40, 0.5)];
    lineView.backgroundColor = [UIColor whiteColor];
    [scrollView addSubview:lineView];
    
    self.verifyTextField = [[LoginTextField alloc] initWithFrame:CGRectMake(20, lineView.bottom, self.view.width - 120, 60)];
    self.verifyTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入验证码" attributes:dict];
    
    UIImageView *verifyImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"leftbar_password"]];
    self.verifyTextField.leftView = verifyImageView;
    self.verifyTextField.leftViewMode = UITextFieldViewModeAlways;
    self.verifyTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.verifyTextField.delegate = self;
    [scrollView addSubview:self.verifyTextField];
    
    self.verifyButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.verifyButton.frame = CGRectMake(self.verifyTextField.right + 10, self.verifyTextField.top + 15, 60, 30);
    [self.verifyButton setTitle:@"验证码" forState:UIControlStateNormal];
    self.verifyButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [self.verifyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UIImage *buttonImage =[UIImage imageNamed:@"btn_border"];
    [self.verifyButton setBackgroundImage:[buttonImage stretchableImageWithLeftCapWidth:5 topCapHeight:5] forState:UIControlStateNormal];
    [self.verifyButton addTarget:self action:@selector(getVerifyCode:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:self.verifyButton];
    
    lineView = [[UIView alloc] initWithFrame:CGRectMake(20, self.verifyTextField.bottom, self.view.width-40, 0.5)];
    lineView.backgroundColor = [UIColor whiteColor];
    [scrollView addSubview:lineView];
    
    self.passwordTextField = [[LoginTextField alloc] initWithFrame:CGRectMake(20, lineView.bottom, self.view.width - 40, 60)];
    self.passwordTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:dict];
    self.passwordTextField.secureTextEntry = YES;
    
    UIImageView *passwordImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"leftbar_password"]];
    self.passwordTextField.leftView = passwordImageView;
    self.passwordTextField.leftViewMode = UITextFieldViewModeAlways;
    self.passwordTextField.delegate = self;
    [scrollView addSubview:self.passwordTextField];
    
    lineView = [[UIView alloc] initWithFrame:CGRectMake(20, self.passwordTextField.bottom, self.view.width-40, 0.5)];
    lineView.backgroundColor = [UIColor whiteColor];
    [scrollView addSubview:lineView];
    
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    nextButton.frame = CGRectMake(lineView.left, lineView.bottom + 50, self.view.width - lineView.left * 2, 40);
    [nextButton setBackgroundImage:[buttonImage stretchableImageWithLeftCapWidth:5 topCapHeight:5] forState:UIControlStateNormal];
    [nextButton setTitle:self.isFromForgotPW ? @"提交" : @"下一步" forState:UIControlStateNormal];
    [nextButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    nextButton.titleLabel.font = [UIFont systemFontOfSize:18.0f];
    [nextButton addTarget:self action:@selector(onNextButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:nextButton];
    
    scrollView.contentSize = CGSizeMake(1, MAX(self.view.height, nextButton.bottom + 30));
}

- (void)getVerifyCode:(UIButton *)sender
{
    [self getVerifyCodeFromServer];
}

- (void)onTimer:(NSTimer *)timer
{
    self.time--;
    if (self.time > 0) {
        [self.verifyButton setTitle:[[NSString alloc] initWithFormat:@"%ld秒",(long)self.time] forState:UIControlStateNormal];
    }else {
        [self.verifyButton setTitle:@"重新获取" forState:UIControlStateNormal];
        [timer invalidate];
        self.time = 60;
        self.verifyButton.enabled = YES;
    }
}

- (void)getVerifyCodeFromServer
{
    if (self.mobileTextField.text.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入手机号码" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        
        return;
    }
    
    self.verifyButton.enabled = NO;
    
    if (self.isFromForgotPW) {
        [LoginRegistNet getForgotPWVerifyCodeWithPhone:self.mobileTextField.text successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            BOOL success = [[responseObject objectForKey:@"success"] boolValue];
            if (success) {
                self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
                [self.timer fire];
            } else {
                NSString *message = [responseObject objectForKey:@"message"];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showText:message time:2];
                });
            }
            
        } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:@"网络连接失败" time:2];
            });
        }];
    } else {
        [LoginRegistNet getVerifyCodeWithPhone:self.mobileTextField.text successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            BOOL success = [[responseObject objectForKey:@"success"] boolValue];
            if (success) {
                self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
                [self.timer fire];
            } else {
                NSString *message = [responseObject objectForKey:@"message"];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showText:message time:2];
                });
            }
            
        } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:@"网络连接失败" time:2];
            });
        }];
    }
}

- (void)onNextButtonClicked:(id)sender
{
    [self.view endEditing:YES];
    
    if (self.isFromForgotPW) {
        [LoginRegistNet resetPasswordWithPhone:self.mobileTextField.text verifyCode:self.verifyTextField.text newPassword:self.passwordTextField.text successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
            BOOL success = [[responseObject objectForKey:@"success"] boolValue];
            if (success) {
                
                [self showText:@"密码修改成功" time:2];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            } else {
                NSString *message = [responseObject objectForKey:@"message"];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showText:message time:2];
                });
            }
        } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:@"网络连接失败" time:2];
            });
        }];
    } else {
        [LoginRegistNet registWithAccount:self.accountTextField.text password:self.passwordTextField.text phone:self.mobileTextField.text verifyCode:self.verifyTextField.text successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            BOOL success = [[responseObject objectForKey:@"success"] boolValue];
            if (success) {
                
                NSDictionary *dataDic = [responseObject objectForKey:@"data"];
                [CurrentUser shareInstance].token = [dataDic objectForKey:@"token"];
                [CurrentUser shareInstance].userId = [[dataDic objectForKey:@"id"] integerValue];
                [CurrentUser shareInstance].sex = [[dataDic objectForKey:@"sex"] integerValue];
                [CurrentUser shareInstance].name = [dataDic objectForKey:@"name"];
                [CurrentUser shareInstance].isLogin = YES;
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    RegistTwoViewController *registTwoViewController = [[RegistTwoViewController alloc] init];
                    [self.navigationController pushViewController:registTwoViewController animated:YES];
                });
            } else {
                NSString *message = [responseObject objectForKey:@"message"];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showText:message time:2];
                });
            }
            
        } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:@"网络连接失败" time:2];
            });
        }];
    }
}

- (void)onBackButton:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onForgotPWButton:(id)sender
{
    RegistViewController *controller = [[RegistViewController alloc] init];
    controller.isFromForgotPW = YES;
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == self.verifyTextField) {
        [self.scrollView setContentOffset:CGPointMake(0, 120) animated:YES];
    } else if (textField == self.passwordTextField) {
        [self.scrollView setContentOffset:CGPointMake(0, 120) animated:YES];
    }
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    [self.scrollView setContentOffset:CGPointZero animated:YES];
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.passwordTextField) {
        [self.view endEditing:YES];
    } else if (textField == self.accountTextField) {
        [self.mobileTextField becomeFirstResponder];
    }
    
    return YES;
}

@end
